package cart

import (
	"strconv"
	"strings"

	"mall/common/globalkey"
	"mall/common/utils/pointy"
	enum "mall/service/backend/common/enum/promotion"
	"mall/service/forum/api/internal/logic/promotion/util"
	"mall/service/forum/api/internal/types"
	"mall/service/promotion/rpc/promotionclient"
	// "github.com/zeromicro/go-zero/core/logx"
)

// CouponInfoHandler 获取优惠券信息handler
type CouponInfoHandler struct {
	// 合成复用Next
	Next
}

// Do 获取优惠券信息
func (h *CouponInfoHandler) Do(c *Context) (err error) {
	// logx.Infow("获取优惠券信息...")

	preload := "coupon:Id,ActivityId,TemplateId,UserId,StartedAt,EndedAt"
	preload += ";couponTemplate:Id,Name,Desc,Members,Type,Mutex,Scope,Mode,Threshhold,DiscountMode,DiscountValue," +
		"PerLimit,ExpireMode,ExpireValue,StartedAt,EndedAt"
	eagerLoad := "couponTemplate:coupon,couponTotal"
	filters := []string{"Status,equalTo:" + strconv.FormatInt(int64(globalkey.StatusStarted), 10)}
	filters = append(filters, "Status,equalTo:"+strconv.FormatInt(int64(globalkey.StatusStarted), 10))
	res, err := c.SvcCtx.PromotionRpc.GetCouponTemlateList(c.Ctx, &promotionclient.BaseListReq{
		Preload:    pointy.GetPointer(preload),
		EagerLoad:  pointy.GetPointer(eagerLoad),
		Filter:     pointy.GetPointer(strings.Join(filters, ";")),
		Sorter:     pointy.GetPointer("Id:0"),
		VisitorId:  pointy.GetPointer(c.UserId),
		PlatformId: pointy.GetPointer(globalkey.ThirdPartyPlatformWechatMini),
	})
	if err != nil {
		return err
	}

	if len(res.List) > 0 {
		for _, v := range res.List {
			var canReceive bool
			var info *promotionclient.CouponInfo
			if v.CouponInfo != nil {
				info = v.CouponInfo
			} else {
				if v.CouponType == nil || *v.CouponType != uint32(enum.PromotionCouponTypeReceive) {
					continue
				}

				if v.PerLimit == nil || *v.PerLimit == 0 {
					canReceive = true
				} else if v.CouponTotal != nil && *v.PerLimit > *v.CouponTotal {
					canReceive = true
				}

				if !canReceive {
					continue
				}
			}

			var timeRange []string
			if v.StartedAt != nil && v.EndedAt != nil {
				timeRange = []string{*v.StartedAt, *v.EndedAt}
			}
			couponTypeText := util.GetCouponTypeText(v.CouponType)
			mutexTypeText := util.GetMutexTypeText(v.MutexType)
			scopeTypeText := util.GetScopeTypeText(v.ScopeType)
			modeText := util.GetCouponModeText(v.Condition)
			discountModeText := util.GetDiscountModeText(v.DiscountMode)
			discount := util.GetDiscountValue(v.DiscountMode, v.DiscountValue)
			expireModeText := util.GetExpireModeText(v.ExpireMode)
			var expire string
			if v.ExpireMode != nil && v.ExpireValue != nil && *v.ExpireMode == uint32(enum.PromotionCouponExpireDynamic) {
				expire = "有效期:" + strconv.FormatInt(int64(*v.ExpireValue), 10) + "天"
			}
			if v.ExpireMode != nil && len(timeRange) > 0 && *v.ExpireMode == uint32(enum.PromotionCouponExpireStatic) {
				expire = "有效期:" + strings.Join(timeRange, " - ")
			}

			couponInfo := &types.CouponInfo{
				CouponTemplateInfo: types.CouponTemplateInfo{
					Id:                v.Id,
					Name:              v.Name,
					Description:       v.Desc,
					MemberRestriction: v.MemberRestriction,
					CouponType:        v.CouponType,
					CouponTypeText:    &couponTypeText,
					MutexType:         v.MutexType,
					MutexTypeText:     &mutexTypeText,
					ScopeType:         v.ScopeType,
					ScopeTypeText:     &scopeTypeText,
					Mode:              v.Condition,
					ModeText:          &modeText,
					Threshold:         v.ConditionValue,
					DiscountMode:      v.DiscountMode,
					DiscountModeText:  &discountModeText,
					DiscountValue:     v.DiscountValue,
					Discount:          &discount,
					PerLimit:          v.PerLimit,
					TimeRange:         timeRange,
					ExpireMode:        v.ExpireMode,
					ExpireModeText:    &expireModeText,
					ExpireValue:       v.ExpireValue,
					Expire:            &expire,
					CouponTotal:       v.CouponTotal,
					CanReceive:        canReceive,
				},
				TemplateId: v.Id,
			}

			if info != nil {
				var infoTimeRange []string
				if info.StartedAt != nil && info.EndedAt != nil {
					infoTimeRange = []string{*info.StartedAt, *info.EndedAt}
				}
				couponInfo.CouponId = info.Id
				couponInfo.ActivityId = info.ActivityId
				couponInfo.TimeRange = infoTimeRange
			}

			c.Resp.CouponList = append(c.Resp.CouponList, couponInfo)
		}
	}

	return
}
